'use strict';

const Controller = require('egg').Controller;

class ExpenseController extends Controller {
    async index() {
        const { ctx, service } = this;
        const { token } = ctx.request.headers;
        const tokenData = service.auth.verifyToken(token);
        if (!tokenData) return ctx.body = { success: false, message: '未登录或token无效' };

        const query = {
            budgetId: ctx.query.budgetId ? Number(ctx.query.budgetId) : undefined,
            startDate: ctx.query.startDate,
            endDate: ctx.query.endDate,
            category: ctx.query.category,
        };
        const result = await service.expense.list(tokenData.userId, query);
        ctx.body = result;
    }

    async create() {
        const { ctx, service } = this;
        const { token } = ctx.request.headers;
        const tokenData = service.auth.verifyToken(token);
        if (!tokenData) return ctx.body = { success: false, message: '未登录或token无效' };

        const payload = ctx.request.body;
        const result = await service.expense.create(tokenData.userId, payload);
        ctx.body = result;
    }

    async update() {
        const { ctx, service } = this;
        const { token } = ctx.request.headers;
        const tokenData = service.auth.verifyToken(token);
        if (!tokenData) return ctx.body = { success: false, message: '未登录或token无效' };

        const id = Number(ctx.params.id);
        const payload = ctx.request.body;
        const result = await service.expense.update(id, tokenData.userId, payload);
        ctx.body = result;
    }

    async destroy() {
        const { ctx, service } = this;
        const { token } = ctx.request.headers;
        const tokenData = service.auth.verifyToken(token);
        if (!tokenData) return ctx.body = { success: false, message: '未登录或token无效' };

        const id = Number(ctx.params.id);
        const result = await service.expense.destroy(id, tokenData.userId);
        ctx.body = result;
    }
}

module.exports = ExpenseController;